import json
from datetime import datetime

from flask import Flask, Blueprint, Response, request
from flask_jwt_extended import jwt_required
from sqlalchemy import and_

from app.common.commonMessage import CommonMassages
from app.model.CalculationModel import CalcuResult
from app.service.industryFlowService import IndustryFlowService
from app.service.invoiceFlowService import InvoiceFlowService
from app.service.belongingFlowService import BelongingFlowService
from app.service.controllerFlowService import ControllerFlowService
from app.service.tradeCrowdService import TradeCrowdService
from app.config.db import DBUtils
from app.config.jsonEncoder import CustomJSONEncoder

app = Flask(__name__)

trade_features_up = Blueprint('trade_features_controller', __name__ , url_prefix='/kshx')

# 获取session
db_utils = DBUtils()
session = db_utils.get_session()

industry_flow = IndustryFlowService()
invoice_flow = InvoiceFlowService()
belonging_flow = BelongingFlowService()
controller_flow = ControllerFlowService()
trade_crowd = TradeCrowdService()

#  获取行业资金流向-流水信息
@trade_features_up.route('/fund_flow', methods=['GET'])
@jwt_required()
def fund_flow_find():
    company = request.args.get('company')
    is_cydw = request.args.get('is_cydw')
    # start_date = request.args.get('start_date')
    # end_date = request.args.get('end_date')
    year = request.args.get('year')
    type = request.args.get('type')
    if year:
        year = int(year)
    else:
        year = datetime.now().year
    # if start_date and end_date:
    #     start_date = datetime.strptime(start_date, '%Y-%m-%d')
    #     end_date =   datetime.strptime(end_date, '%Y-%m-%d')
    # else:
    #     start_date = ''
    #     end_date = ''

    if company and is_cydw and type:
        if int(is_cydw) in [2, 3]:
            result = session.query(CalcuResult.JSONDATA).filter(
                and_(
                    CalcuResult.GSMC == company,
                    CalcuResult.TYPE == type,
                    CalcuResult.JYND == year
                )
            ).scalar()
            fund_flow_info = json.loads(result)
        else:
            if type == 'industry':
                # 行业流向
                fund_flow_info = industry_flow.select_industry_flow_info(session, company, is_cydw, year)
            elif type == 'invoice':
                # 发票流向
                fund_flow_info = invoice_flow.select_invoice_flow_info(session, company, is_cydw, year)
            elif type == 'belonging':
                # 归属流向
                fund_flow_info = belonging_flow.select_belonging_flow_info(session, company, is_cydw, year)
            elif type == 'controller':
                # 实际控制人流向
                fund_flow_info = controller_flow.select_controller_flow_info(session, company, is_cydw, year)
            else:
                fund_flow_info = ''
        if fund_flow_info:
            result = {
                "code": 200,
                "data": fund_flow_info,
                "message": CommonMassages.CCD_SELECT_SUCCESS.value
            }
        else:
            result = {
                "code": 400,
                "data": None,
                "message": CommonMassages.CCD_SELECT_FAILED.value
            }
    else:
        result = {
            "code": 400,
            "data": None,
            "message": CommonMassages.CCD_SELECT_FAILED.value
        }
    resp_data = json.dumps(result, ensure_ascii=False, cls=CustomJSONEncoder)
    return Response(resp_data)

# 获取交易圈信息
@trade_features_up.route('/trade_crowd', methods=['GET'])
@jwt_required()
def trade_crowd_find():
    company = request.args.get('company')
    is_cydw = request.args.get('is_cydw')
    start_date = request.args.get('start_date')
    end_date = request.args.get('end_date')
    if start_date and end_date:
        start_date = datetime.strptime(start_date, '%Y-%m-%d')
        end_date =   datetime.strptime(end_date, '%Y-%m-%d')
    else:
        start_date = datetime.now().replace(month=1, day=1).strftime('%Y-%m-%d')
        end_date = datetime.now().strftime('%Y-%m-%d')
    if company and is_cydw:
        if int(is_cydw) in [2, 3]:
            result = session.query(CalcuResult.JSONDATA).filter(
                and_(
                    CalcuResult.GSMC == company,
                    CalcuResult.TYPE == 'cd',
                    CalcuResult.JYND == start_date.year
                )
            ).scalar()
            trade_crowd_info = json.loads(result)
        else:
            trade_crowd_info = trade_crowd.select_trade_crowd_info(session, company, is_cydw, start_date, end_date)
        if trade_crowd_info:
            result = {
                "code": 200,
                "data": trade_crowd_info,
                "message": CommonMassages.CCD_SELECT_SUCCESS.value
            }
        else:
            result = {
                "code": 400,
                "data": None,
                "message": CommonMassages.CCD_SELECT_FAILED.value
            }
    else:
        result = {
            "code": 400,
            "data": None,
            "message": CommonMassages.CCD_SELECT_FAILED.value
        }
    resp_data = json.dumps(result, ensure_ascii=False, cls=CustomJSONEncoder)
    return Response(resp_data)